// MainFrm.cpp : implementation of the CMainFrame class
//

#include "stdafx.h"
#include "Finance.h"
#include "CDataFile.h"
#include "financedef.h"
#include "cshellfileop.h"

#include "DlgManage.h"

#include "MPIChildFrame.h"
#include "MainFrm.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CMainFrame

IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd)
	//{{AFX_MSG_MAP(CMainFrame)
	ON_WM_CREATE()
	ON_COMMAND(ID_CALC, OnCalc)
	ON_COMMAND(ID_MANAGE, OnManage)
	ON_COMMAND(ID_DUAL, OnDual)
	ON_UPDATE_COMMAND_UI(ID_DUAL, OnUpdateDual)
	ON_COMMAND(ID_APP_HELP, OnAppHelp)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

static UINT indicators[] =
{
	ID_SEPARATOR,           // status line indicator
	ID_INDICATOR_DATERANGE,
	ID_INDICATOR_LSTCOUNT,
	ID_INDICATOR_AVERAGE
};

/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction

CMainFrame::CMainFrame()
{
	// TODO: add member initialization code here
	m_bSplit = FALSE;
}

CMainFrame::~CMainFrame()
{
}

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
		| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
		!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
	{
		TRACE0("Failed to create toolbar\n");
		return -1;      // fail to create
	}
	
	// set toolbar24
	m_wndToolBar.SetButtonText(  0, "Setup" );
	m_wndToolBar.SetButtonText(  1, "Calc" );
	m_wndToolBar.SetButtonText(  2, "Manage" );
	m_wndToolBar.SetButtonText(  3, "Refresh" );
	m_wndToolBar.SetButtonText(  4, "Search" );
	m_wndToolBar.SetButtonText(  5, "TreeView" );
	
	m_wndToolBar.SetButtonText( 7, "Append" );
	m_wndToolBar.SetButtonText( 8, "Delete" );
	m_wndToolBar.SetButtonText( 9, "Modify" );
	
	m_wndToolBar.SetButtonText( 11, "Help" );
	m_wndToolBar.SetButtonText( 12, "About" );
	m_wndToolBar.SetButtonText( 13, "Exit" );
	
	// the first CSize( w, h ) must fit with the text in button
	m_wndToolBar.SetSizes( CSize( 67, 44 ), CSize(24,24) );
	
	
	int i,j=m_wndToolBar.GetToolBarCtrl().GetButtonCount();
	LPRECT btnpos=new RECT[j+1];
	for(i=0;i<j;i++)
		m_wndToolBar.GetItemRect(i,&btnpos[i]);
	
	// <> note the tool button must be 24 x 24, it be fixed in CToolBar24::SetFullColorImage()
	m_wndToolBar.SetFullColorImage( IDB_TBR24, RGB(255, 0, 255),btnpos,j);
	RECT		rc;
	GetClientRect( &rc );
	
	
	if (!m_wndStatusBar.Create(this) ||
		!m_wndStatusBar.SetIndicators(indicators,
		sizeof(indicators)/sizeof(UINT)))
	{
		TRACE0("Failed to create status bar\n");
		return -1;      // fail to create
	}
	
	m_wndStatusBar.SetPaneInfo( 1, ID_INDICATOR_DATERANGE, SBPS_NORMAL, 130 );
	m_wndStatusBar.SetPaneInfo( 2, ID_INDICATOR_LSTCOUNT, SBPS_NORMAL, 140 );
	m_wndStatusBar.SetPaneInfo( 3, ID_INDICATOR_AVERAGE, SBPS_NORMAL, 360 );
	
	// TODO: Delete these three lines if you don't want the toolbar to
	//  be dockable
	m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
	EnableDocking(CBRS_ALIGN_ANY);
	DockControlBar(&m_wndToolBar);
	
	// Auto Backup mdb
	BackupMDB();

	return 0;
}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
	if( !CMDIFrameWnd::PreCreateWindow(cs) )
		return FALSE;
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs
	cs.x = 0;
	cs.y = 0;

	INT	iScreenW = GetSystemMetrics( SM_CXSCREEN );
	INT	iScreenH = GetSystemMetrics( SM_CYSCREEN );
	if( iScreenW >= 1024 ) 
	{
		cs.cx = 1024;
		cs.cy = 735;
	}
	else
	{
		cs.cx = 805;
		cs.cy = 575;
	}
	
	return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
	CMDIFrameWnd::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
	CMDIFrameWnd::Dump(dc);
}

#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers


// 
//--------------------------------------------------------------
void CMainFrame::OnUpdateFrameTitle(BOOL bAddToTitle)
{
	CMDIFrameWnd::OnUpdateFrameTitle(FALSE);
}

// 
//--------------------------------------------------------------
void CMainFrame::UpdateMenu(HMENU hMenu)
{

}

// 
// 
//--------------------------------------------------------------
void CMainFrame::OnCalc() 
{
	WinExec( "calc.exe", SW_SHOW );
}

// 
// 
//--------------------------------------------------------------
void CMainFrame::OnManage() 
{
	CDlgManage	dlg;
	
	dlg.DoModal();
	
}

// 
//--------------------------------------------------------------
void CMainFrame::OnDual() 
{
	CMPIChildFrame* pFrameWnd = (CMPIChildFrame*)MDIGetActive( FALSE );
	
	CSplitterWnd*	pSplitter = pFrameWnd->GetSpliterPtr( 1 );
	if( pSplitter )
	{
		if( m_bSplit ) 
		{
			pSplitter->SetColumnInfo( 0, 0, 0 );
			m_bSplit = FALSE;
		}
		else
		{
			pSplitter->SetColumnInfo( 0, 360, 0 );
			m_bSplit = TRUE;
		}
		pSplitter->RecalcLayout();
	}
}

// 
//--------------------------------------------------------------
void CMainFrame::OnUpdateDual(CCmdUI* pCmdUI) 
{
	pCmdUI->SetCheck( m_bSplit );
}


// !!!
// Invoke ".chm" in VC
// <1> include "htmlhelp.h" in "StdAfx.h"
// <2> Set Additional include dir for "htmlhelp.h"
// <3> inport "htmlhelp.lib" in Link input
// <4> Set Additional library path in Link 
// <5> Add below code to invoke ".chm"
//--------------------------------------------------------------
void CMainFrame::OnAppHelp() 
{
	OnExecHelper();
}

// 
// Auto backup
//-----------------------------------------------------------------------------------------
void CMainFrame::BackupMDB()
{
	CShellFileOp	op, opcpy;
	BOOL			bSuccess = TRUE, bAPICalled = FALSE, bAborted = FALSE;
	int				nAPIReturn = 0;
	CString			csAbsPath;
	CString			strMsg;
	HANDLE 				hFind;
  	WIN32_FIND_DATA 	FindFileData;
	CDataFile			IniDF( MONEY_CFG );
	t_Str				sdStrTmp;
	CHAR				chSQL[MAX_PATH+100] = { 0 };
	DWORD				dwRet;


	// <> Get current path segment and init edit
	sdStrTmp = IniDF.GetValue( "BakPath", "Backup segment" );
	if( 0 == sdStrTmp.length() )
	{
		dwRet = GetCurrentDirectory( MAX_PATH, chSQL );
		if( dwRet == 0 ) 
		{
			sprintf( chSQL, "GetCurrentDirectory failed (%d)\n", GetLastError() );
			AfxMessageBox( chSQL, MB_ICONERROR );
			return ;
		}
		
		if( dwRet > MAX_PATH ) 
		{
			sprintf( chSQL, "GetCurrentDirectory failed (buffer too small; need %d chars)\n", dwRet );
			AfxMessageBox( chSQL, MB_ICONERROR );
			return ;
		}

		// other cause is ok
	}
	else
	{
		sdStrTmp.copy( chSQL, sdStrTmp.length(), 0 );
	}

	// <> Dest abs path for backup file
	strcat( chSQL, "\\" );
	csAbsPath = chSQL;
	csAbsPath += BACKUPFILE;
	

	// <> find bak file first,
 	hFind = FindFirstFileA( csAbsPath, &FindFileData );
	
	// <> if the bak file exist, dele then, 
  	if( hFind != INVALID_HANDLE_VALUE ) 
  	{
	    FindClose( hFind );

		// <> Del old bak.mdb
		bSuccess = FALSE;

		op.SetOperationFlags(  FO_DELETE, this,
								FOF_FILESONLY | FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION );
 
		op.AddSourceFile( csAbsPath );

		op.AddDestFile( csAbsPath );

		bSuccess = op.Go( &bAPICalled, &nAPIReturn, &bAborted );
  	}

	// <> backup now
	if( bSuccess ) 
	{
		// <> Backup new bak.mdb
		opcpy.SetOperationFlags(  FO_COPY, this,
								FOF_FILESONLY | FOF_NOCONFIRMATION | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION );
 
		opcpy.AddSourceFile( "Mmoney.mdb" );

		opcpy.AddDestFile( csAbsPath );

		bSuccess = opcpy.Go( &bAPICalled, &nAPIReturn, &bAborted );
		if( bSuccess ) 
		{
			; //MessageBox( "Mmoney.mdb backup to Mmoney_bak.mdb successfully!", "Remind", MB_ICONINFORMATION );
		}
		else
		{
			MessageBox( "Mmoney.mdb backup to Mmoney_bak.mdb unsuccessfully!\nPlease backup the Mmoney.mdb manually!", "Remind", MB_ICONWARNING );
		}
	}
	else
	{
		strMsg.Format( _T("CShellFileOp::Go() returned %s.\n\nbAPICalled = %s\nnAPIReturn = %d\nbAborted = %s"),
						 bSuccess ? _T("TRUE") : _T("FALSE"),
						 bAPICalled ? _T("TRUE") : _T("FALSE"),
						 nAPIReturn,
						 bAborted ? _T("TRUE") : _T("FALSE") );
 
		 AfxMessageBox( strMsg, MB_ICONINFORMATION );
	}

}
